package cn.edu.lingnan.controller;


import cn.edu.lingnan.common.Result;
import cn.edu.lingnan.entity.dto.SubmitDto;
import cn.edu.lingnan.entity.Prove;
import cn.edu.lingnan.entity.Team;
import cn.edu.lingnan.mapper.ProveMapper;
import cn.edu.lingnan.service.ITeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;



@RestController
@RequestMapping("/Team")
public class TeamController {
    @Autowired
    private ITeamService teamService;

    @Autowired
    private ProveMapper proveMapper;

    @PostMapping("/submitForm")
    public Result submitForm(@RequestBody SubmitDto submitDto){
        System.out.println(submitDto);
        Team team = teamService.teamSave(submitDto);
        String teamId = team.getTeamId();
        System.out.println(team);
        return Result.success(teamId);
    }

    @PostMapping("/submitDoc")
    public void submitDoc(@RequestParam String id, MultipartFile[] file){
        System.out.println(id);
        Prove prove = new Prove();
        for (MultipartFile f:file
             ) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String originalFilename = f.getOriginalFilename();
            String FileName = originalFilename.substring(0, originalFilename.lastIndexOf('.'));
            int length = originalFilename.length();
            String HouZhui = originalFilename.substring(originalFilename.lastIndexOf('.'),length);
            System.out.println(HouZhui);
            String format = simpleDateFormat.format(new Date());
            String s = id + "-"+format + FileName+ UUID.randomUUID();
            System.out.println(s);


            //动态获取当前项目所在路径
            String path= System.getProperty("user.dir") + File.separator + "DaoChu";
            System.out.println(path);


            File file1 = new File(path,"_"+id);
            if (!file1.exists()){
                file1.mkdirs();

            }
            String savePath = path + File.separator+"_"+id;
            String fileName = s+HouZhui;

            //上传文件
            File file2 = new File(savePath,fileName);
            try {
                f.transferTo(file2);

            } catch (IOException e) {
                 e.printStackTrace();
                 return;
            }
            prove.setId(String.valueOf(UUID.randomUUID()));
            prove.setAwardId(id);
            prove.setProveName(fileName);
            proveMapper.insert(prove);



        }


    }

}
